package proxy;

import DAO.FoundRecordDAO;
import entity.FoundRecord;
import entity.Log;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import service.Impl.LogServiceImpl;
import type.OperationType;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

public class FoundRecordDaoProxyFactory implements MethodInterceptor {
    private Object target;
    private String currentLoginName;

    public void setTarget(Object target) {
        this.target = target;
    }

    public void setCurrentLoginName(String name) {
        this.currentLoginName = name;
    }

    public FoundRecordDAO createProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return (FoundRecordDAO) enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        long startTime = System.currentTimeMillis();
        boolean success = false;
        try {
            Object result = proxy.invokeSuper(obj, args);
            success = true;
            return result;
        } finally {
            long duration = System.currentTimeMillis() - startTime;
            recordOperationLog(method, args, success, duration);
        }
    }

    private void recordOperationLog(Method method, Object[] args, boolean success, long duration) {
        try {
            String methodName = method.getName();
            OperationType operationType = getOperationType(methodName);
            String details = buildOperationDetails(args);

            String logMessage = String.format(
                    operationType.getDescription(),
                    details,
                    duration);

            if (!success) {
                logMessage = "失败 - " + logMessage;
            }

            Log log = new Log(
                    currentLoginName,
                    logMessage,
                    LocalDateTime.now()
            );

            new LogServiceImpl().recordlog(log);
        } catch (Exception e) {
            System.err.println("记录日志失败: " + e.getMessage());
        }
    }

    private String buildOperationDetails(Object[] args) {
        if (args != null && args.length > 0 && args[0] instanceof FoundRecord) {
            FoundRecord record = (FoundRecord) args[0];
            return String.format("用户ID:%d",
                    record.getId() != null ? record.getId() : -1,
                    record.getUserId() != null ? record.getUserId() : -1);
        }
        return "";
    }

    private OperationType getOperationType(String methodName) {
        if (methodName == null) {
            return OperationType.UNKNOW_OPERATION;
        }

        switch (methodName) {
            case "addFoundRecord":
                return OperationType.ADD;
            case "deleteFoundRecord":
                return OperationType.DELETE;
            case "updateFoundRecord":
                return OperationType.UPDATE;
            case "selectFoundRecord":
                return OperationType.SELECT;
            default:
                return OperationType.UNKNOW_OPERATION;
        }
    }

    public void setCurrentLoningName(String loginName) {
    }
}

